package com.zretc.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.google.gson.Gson;
import com.sun.org.apache.xpath.internal.compiler.Keywords;
import com.zretc.entity.Product;
import com.zretc.entity.Seller;
import com.zretc.entity.Type;
import com.zretc.entity.User;
import com.zretc.service.ProductService;
import com.zretc.service.TypeService;
import com.zretc.service.impl.ProductServiceImpl;
import com.zretc.service.impl.TypeServiceImpl;
import com.zretc.util.PageInfo;
/**
 * Servlet implementation class BackSellerProductServlet
 */
@WebServlet("/back/SellerProductServlet")
@MultipartConfig
public class SellerProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	// 获取商品业务层对象
		private ProductService productService = new ProductServiceImpl();
		
		private TypeService typeService = new TypeServiceImpl();

		@Override
		protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			// 获取操作类型
			String op = request.getParameter("op");
			/*if(op == null) {
				op = "";
			}*/
			
			// 判断操作类型
			switch (op) {
			case "getAll":
				// 根据条件获取在售商品并排序
				getProductList(request, response);
				break;
			case "soldOut":
				// 下架商品
				soldOutProduct(request, response);
				break;
				// 根据条件获取全部商品
			case "getLike":
				getProductLike(request,response);
				break;
			case "deleteProduct":
				deleteProduct(request,response);
				break;
			case "insertProduct":
				insertProduct(request,response);
				break;
			case "getType":
				getType(request,response);
				break;
			case "soldon":
				soldOnProduct(request,response);
				break;
			case "updateInventory":
				// 根据条件获取在售商品并排序
				updateInventoryProductList(request, response);
				break;
			default:
				break;
			}
		}
		
		private void updateInventoryProductList(HttpServletRequest request, HttpServletResponse response) {
			Integer productId = Integer.valueOf(request.getParameter("productId"));
			Product product = productService.getProductByProductId(productId);
			Integer productInventory=Integer.valueOf(request.getParameter("productInventory"));
			product.setProductInventory(productInventory);
			productService.updateProduct(product);
			
		}

		private void soldOnProduct(HttpServletRequest request, HttpServletResponse response) {
			// 获取商品id
						Integer productId = Integer.valueOf(request.getParameter("productId"));
						
						// 根据商品id获取商品
						Product product = productService.getProductByProductId(productId);
						// 设置为上架状态
						product.setProductStatus(1);
						// 更新商品
						productService.updateProduct(product);
		}

		private void insertProduct(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
			//解析json字符串
			
				Part part = request.getPart("productPicture");
				
				String productName=request.getParameter("productName");
				Integer sellerId = Integer.valueOf(request.getParameter("sellerId"));
				Seller seller =new Seller();
				seller.setSellerId(sellerId);
				Integer productInventory = Integer.valueOf(request.getParameter("productInventory"));
				Float productPrice=Float.parseFloat(request.getParameter("productPrice"));
				Integer typeId = Integer.valueOf(request.getParameter("typeId"));
				Type type = new Type();
				type.setTypeId(typeId);
				
				String productTime=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
				
				Integer productStatus = Integer.valueOf(request.getParameter("productStatus"));
				String productIntroduce=request.getParameter("productIntroduce");
				// 获取文件真实名:Servlet 3.0不提供获取上传文件名的方法,通过请求头信息间接获取
				String header = part.getHeader("content-disposition");
			
				String realName=header.substring(header.indexOf("filename=")+10,header.length()-1);
				// 获取真实文件名的后缀
				String fileSuffix = realName.substring(realName.lastIndexOf("."));
				
				// 使用时间戳+随机数自动生成文件名,避免文件名重复问题
				// JDK1.8 日期时间类
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
				// 将当前日期时间转成字符串
				String formatDate = ofPattern.format(now);	
				// 随机数
				int random = (int) (Math.random()*1000+1);
				// 拼接
				StringBuffer fileName = new StringBuffer();
				fileName.append(formatDate).append(random);
				
				// 将文件存储在指定服务器中(本地电脑E盘)
				File file = new File("D:\\upload\\images");
				
				// 将文件写入指定位置
				String filePath = file.getPath() + File.separator + fileName + fileSuffix; // E:\fileupload\images\1.jpg
				part.write(filePath);
				System.out.println("上传文件成功!");
				
				Product product=new Product(null, productName, seller, productInventory, productPrice, fileName + fileSuffix, type, productTime, productStatus, productIntroduce);
				productService.insertProduct(product);
				getProductLike(request,response);
				
			}
			
		/*}*/

		private void deleteProduct(HttpServletRequest request, HttpServletResponse response) throws IOException {
			// 获取商品id
						Integer productId = Integer.valueOf(request.getParameter("productId"));
						
						// 根据商品id获取商品
						Product product = productService.getProductByProductId(productId);
						
						// 删除
						productService.deleteProduct(productId);
						// 响应json
						response.setContentType("application/json");
						response.getWriter().write(new Gson().toJson(product));
			
		}

		private void getProductLike(HttpServletRequest request, HttpServletResponse response) throws IOException {
			String pageNum = request.getParameter("pageNum");
			if("".equals(pageNum)) {
				pageNum = "10";
			}
			// 获取页码
			String pageSize = request.getParameter("pageSize");
			if("".equals(pageSize)) {
				pageSize = "1";
			}
			String keyword =request.getParameter("keyword");
			//获取sellerId
			String sellerId=request.getParameter("sellerId");
			
			// 构建map条件
			Map<String, String> condition = new HashMap<>();
			condition.put("pageNum", pageNum);
			condition.put("pageSize", pageSize);
			condition.put("keyword", keyword);
			condition.put("sellerId", sellerId);
			PageInfo<Product> pageInfo=productService.productListBySellerIdandKeyword(condition);
			// 响应json
			response.setContentType("application/json");
			response.getWriter().write(new Gson().toJson(pageInfo));
		}

		/**
		 * wentao
		 * @param request 请求
		 * @param response 响应
		 * @throws ServletException 异常
		 * @throws IOException 异常
		 */
		/**
		 * @param request
		 * @param response
		 * @throws ServletException
		 * @throws IOException
		 */
		public void getProductList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			// 获取显示数量
			String pageNum = request.getParameter("pageNum");
			if("".equals(pageNum)) {
				pageNum = "10";
			}
			// 获取页码
			String pageSize = request.getParameter("pageSize");
			if("".equals(pageSize)) {
				pageSize = "1";
			}
			String keyword =request.getParameter("keyword");
			//获取sellerId
			String sellerId=request.getParameter("sellerId");
			
			// 构建map条件
			Map<String, String> condition = new HashMap<>();
			condition.put("pageNum", pageNum);
			condition.put("pageSize", pageSize);
			condition.put("keyword", keyword);
			condition.put("sellerId", sellerId);
			
			
			// 分页查询数据
			PageInfo<Product> pageInfo = productService.productListBySellerIdandKeywordandStatus(condition);
			// 响应json
			response.setContentType("application/json");
			response.getWriter().write(new Gson().toJson(pageInfo));
		}
		
		/**
		 * @author SUFAN
		 * 下架商品
		 */
		public void soldOutProduct(HttpServletRequest request, HttpServletResponse response) {
			// 获取商品id
			Integer productId = Integer.valueOf(request.getParameter("productId"));
			
			// 根据商品id获取商品
			Product product = productService.getProductByProductId(productId);
			// 设置为下架状态
			product.setProductStatus(0);
			// 更新商品
			productService.updateProduct(product);
		}
		
		public void getProductDetail(HttpServletRequest request, HttpServletResponse response) throws IOException {
			// 获取商品id
			Integer productId = Integer.valueOf(request.getParameter("productId"));
			// 根据商品id获取商品
			Product product = productService.getProductByProductId(productId);
			
			// 响应json
			response.setContentType("application/json");
			response.getWriter().write(new Gson().toJson(product));
		}
		
		public void getType(HttpServletRequest request, HttpServletResponse response) throws IOException {
			// 获取分类父编号
			Integer typeFatherId = Integer.valueOf(request.getParameter("typeFatherId"));
			// 根据父类查询分类
			List<Type> list = typeService.typeListByFatherId(typeFatherId);
			
			// 响应json
			response.setContentType("application/json");
			response.getWriter().write(new Gson().toJson(list));
		}
		

	}
